/*
 * @Description: axios请求封装
 * @Author: wangfuwei
 * @Date: 2020-11-30 18:31:23
 * @LastEditors: wangfuwei
 * @LastEditTime: 2021-04-25 21:28:59
 * @FilePath: /horizon-frontend/src/utils/request.js
 */
import Vue from "vue";
import axios from "axios";
import store from "@/store";
import notification from "ant-design-vue/es/notification";
import { VueAxios } from "./axios";
import { ACCESS_TOKEN, ACCESS_TOKEN_ALIVE, ACCEPT_LANGUAGE, Content_Type } from "@/core/const";
import { TOKEN } from "@/store/mutation-types";
import { getLanguage } from "@/locales/util";

const request = axios.create({
  baseURL: "http://localhost:8080", // API 请求的默认前缀
  timeout: 6 * 1000, // 请求超时时间
});

// 异常拦截处理器
const errorHandler = error => {
  if (error.response) {
    if (error.response.status === 403) {
      //资源禁止
      notification.error({
        message: "Forbidden",
        description: "Resource access is forbidden",
      });
    } else if (error.response.status === 401 && !error.response.data) {
      //没有权限
      notification.error({
        message: "Unauthorized",
        description: "Authorization verification failed",
      });

      //如果已登录则退出
      Vue.ls.get(ACCESS_TOKEN) && store.dispatch("user/logout").then(() => setTimeout(() => window.location.reload(), 1500));
    }
  }

  console.error(error);
  return Promise.reject(error);
};

// 请求拦截器
request.interceptors.request.use(config => {
  Vue.ls.get(ACCESS_TOKEN) && (config.headers[ACCESS_TOKEN] = Vue.ls.get(ACCESS_TOKEN));
  config.headers[ACCEPT_LANGUAGE] = getLanguage();
  config.headers["Content-Type"] || (config.headers["Content-Type"] = Content_Type.JSON);
  return config;
}, errorHandler);

// 响应拦截器
request.interceptors.response.use(response => {
  const token = response.headers[ACCESS_TOKEN.toLocaleLowerCase()];
  const token_alive = response.headers[ACCESS_TOKEN_ALIVE.toLocaleLowerCase()];
  token && token_alive && (Vue.ls.set(ACCESS_TOKEN, token, token_alive) || store.commit("user/" + TOKEN, token));
  return response.data;
}, errorHandler);

// 全局注册Vue.$http 和 Vue.axios
const installer = {
  install(Vue) {
    Vue.use(VueAxios, request);
  },
};

export default request;

export { installer as VueAxios, request as axios };
